package com.qiantu.phone.ui.activity;

import static com.qiantu.phone.BuildConfig.OBS_BASE;

import android.Manifest;
import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.lifecycle.LifecycleOwner;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hjq.base.BaseActivity;
import com.hjq.base.BaseAdapter;
import com.hjq.base.BaseDialog;
import com.hjq.http.listener.HttpCallback;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.XXPermissions;
import com.hjq.toast.ToastUtils;
import com.lxj.xpopup.XPopup;
import com.qiantu.api.db.LLDeviceDBManager;
import com.qiantu.api.db.LLFloorDBManager;
import com.qiantu.api.db.LLRoomDBManager;
import com.qiantu.api.db.LLSceneDBManager;
import com.qiantu.api.entity.DeviceBean;
import com.qiantu.api.entity.FloorBean;
import com.qiantu.api.entity.RoomBean;
import com.qiantu.api.entity.SceneBean;
import com.qiantu.api.http.LLHttpManager;
import com.qiantu.api.http.model.HttpData;
import com.qiantu.phone.R;
import com.qiantu.phone.app.AppActivity;
import com.qiantu.phone.app.AppApplication;
import com.qiantu.phone.event.RefreshDeviceListEvent;
import com.qiantu.phone.event.RefreshFloorRoomEvent;
import com.qiantu.phone.manager.ActivityManager;
import com.qiantu.phone.manager.OBSManager;
import com.qiantu.phone.ui.adapter.ListLabelAdapter;
import com.qiantu.phone.ui.dialog.BottomEditDialog;
import com.qiantu.phone.ui.dialog.BottomListDialog;
import com.qiantu.phone.ui.dialog.ConfirmCancelHintDialog;
import com.qiantu.phone.ui.dialog.ConfirmHintDialog;
import com.qiantu.phone.utils.Constants;
import com.qiantu.phone.utils.GetJsonDataUtil;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

public class FloorSettingActivity  extends AppActivity {
    private static final int EDIT_ROOM_CODE = 666;
    private String roomName;
    private int type;
    private FloorBean floorBean;
    private BottomEditDialog mBottomEditDialog;
    private LinearLayout nameLayout;
    private TextView tvRoomPic;
    private LinearLayout deviceLayout;
    private LinearLayout sceneLayout;
    private LinearLayout deleteLayout;
    private TextView tvRoomName;
    private TextView tvSceneNum;
    private TextView tvDeviceNum;
    private BottomListDialog mBottomListDialog;
    private String currentAction; // 添加成员变量保存当前action

    @Override
    protected int getLayoutId() {
        return R.layout.floor_setting_activity;
    }

    @Override
    protected void initView() {
        type = getInt("type");
        nameLayout = findViewById(R.id.btn_room);
        deviceLayout = findViewById(R.id.scene_num);
        sceneLayout = findViewById(R.id.device_num);
        tvRoomName = findViewById(R.id.tv_room_name);
        tvRoomPic = findViewById(R.id.tv_room_pic);
        tvSceneNum = findViewById(R.id.tv_scene_num);
        tvDeviceNum = findViewById(R.id.tv_device_num);
        deleteLayout = findViewById(R.id.delete_layout);
//        initViewPager();
        setOnClickListener(R.id.btn_room, R.id.btn_delete, R.id.btn_picture);
        if(type == 2){
            nameLayout.setVisibility(View.GONE);
            deleteLayout.setVisibility(View.GONE);
            getTitleBar().setTitle("全屋设置");
            tvRoomPic.setText("全屋图片");
        }else{
            getTitleBar().setTitle("楼层设置");
            tvRoomPic.setText("楼层图片");
            ((TextView)findViewById(R.id.btn_delete)).setText("删除楼层");
        }
    }

    private void updateRoomName() {
        tvRoomName.setText(floorBean.getFloorName());
    }

    @Override
    protected void initData() {
        String floorSerialNo = getIntent().getStringExtra("floorSerialNo");
        floorBean = LLFloorDBManager.getInstance(getContext()).getFloorByFloorSerialNo(floorSerialNo);
        List<SceneBean> scenes;
        List<DeviceBean> devices;
        if(floorBean.getType() == 1){
            devices = LLDeviceDBManager.getInstance(getContext()).getAvailableDevices();
            scenes = LLSceneDBManager.getInstance(getContext()).getAll();
        }else{
            scenes = LLSceneDBManager.getInstance(getContext()).getSceneByFloor(floorSerialNo);
            devices = LLDeviceDBManager.getInstance(getContext()).getHomeAvailableDeviceByFloor(floorSerialNo);
        }
        tvSceneNum.setText(scenes.size() + "");
        tvDeviceNum.setText(devices.size() + "");
        updateRoomName();
    }

    private BaseDialog mConfirmCancelHintDialog;
    private ConfirmCancelHintDialog.Builder mConfirmCancelHintDialogBuilder;

    private void showDeleteHintDialog() {
        if (mConfirmCancelHintDialog == null) {
            mConfirmCancelHintDialogBuilder = new ConfirmCancelHintDialog.Builder(getActivity());
            mConfirmCancelHintDialog = mConfirmCancelHintDialogBuilder.create();
        }
        mConfirmCancelHintDialogBuilder.setListener(new ConfirmCancelHintDialog.OnListener() {
            @Override
            public void onLeftClick(BaseDialog dialog) {
                mConfirmCancelHintDialogBuilder.dismiss();
            }

            @Override
            public void onRightClick(BaseDialog dialog) {
                mConfirmCancelHintDialogBuilder.dismiss();
                Map data = new HashMap<>();
                //1房间绑定 2房屋绑定(移除房间,绑定到房屋)
                data.put("floorSerialNo", floorBean.getFloorSerialNo());
                LLHttpManager.deleteFloor(FloorSettingActivity.this, data,
                        new HttpCallback<HttpData<Void>>(FloorSettingActivity.this) {
                            @Override
                            public void onStart(Call call) {
                                showDialog(null);
                            }

                            @Override
                            public void onSucceed(HttpData<Void> result) {
                                if (result.isRequestSucceed()) {
                                    LLFloorDBManager.getInstance(getContext()).remove(floorBean);
                                    EventBus.getDefault().post(new RefreshFloorRoomEvent());
                                    toast(R.string.delete_success);
                                    setResult(RESULT_OK);
                                    finish();
                                }
                            }

                            @Override
                            public void onFail(Exception e) {
                                super.onFail(e);
                            }
                        });
            }
        });
        mConfirmCancelHintDialogBuilder.setContent(getString(R.string.delete_room_hint));
        mConfirmCancelHintDialog.show();
    }

    private void showBottomEditDialog(String text) {
        if (mBottomEditDialog == null) {
            mBottomEditDialog = new BottomEditDialog(this);
            mBottomEditDialog.setDialogClickListener(new BottomEditDialog.DialogClickListener() {
                @Override
                public void onConfirmClick() {
                    String text = mBottomEditDialog.getText();
                    if (TextUtils.isEmpty(text)) {
                        toast("请输入楼层名称");
                        return;
                    }
                    Map<String, Object> data = new HashMap<>();
                    data.put("floorSerialNo", floorBean.getFloorSerialNo());
                    data.put("newName", text);
                    LLHttpManager.editFloorName((LifecycleOwner) getContext(), data, new HttpCallback<HttpData<Void>>(FloorSettingActivity.this) {
                        @Override
                        public void onSucceed(HttpData<Void> result) {
                            floorBean.setFloorName(mBottomEditDialog.getText());
                            tvRoomName.setText(mBottomEditDialog.getText());
                            LLFloorDBManager.getInstance(getContext()).put(floorBean);
                            EventBus.getDefault().post(new RefreshFloorRoomEvent());
                            setResult(RESULT_OK);
                            toast(R.string.reset_success);
                        }

                        @Override
                        public void onFail(Exception e) {
                            super.onFail(e);
                        }
                    });
                }
            });
            new XPopup.Builder(this)
                    .dismissOnBackPressed(true)
                    .enableDrag(true)
                    .asCustom(mBottomEditDialog);
        }
        mBottomEditDialog.setLabel(getString(R.string.room_name));
        mBottomEditDialog.setText(text);
        mBottomEditDialog.setMaxLength(Constants.ROOM_NAME_MAX_LENGTH);
        mBottomEditDialog.show();
    }

    @Override
    public void onResume() {
        super.onResume();
        initData();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_room:
                showBottomEditDialog(tvRoomName.getText().toString());
                break;
            case R.id.btn_delete:
                showDeleteHintDialog();
                break;
            case R.id.btn_picture:
                showBottomListDialog();
                break;
        }
    }

    private void showBottomListDialog() {
        if (mBottomListDialog == null) {
            mBottomListDialog = new BottomListDialog(getContext());
            mBottomListDialog.setDialogClickListener(new BottomListDialog.DialogClickListener() {
                @Override
                public void onConfirmClick() {

                }
            });
            ListLabelAdapter listLabelAdapter = new ListLabelAdapter(getContext());
            listLabelAdapter.setChecekSelect(true);
            List<String> data = new ArrayList<>();
            data.add(getString(R.string.room_picture_gallery));
            data.add("从相册选择");
            data.add("照相");
            listLabelAdapter.setData(data);
            listLabelAdapter.setOnItemClickListener(new BaseAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(RecyclerView recyclerView, View itemView, int position) {
                    mBottomListDialog.dismiss();
                    String key = data.get(position);
                    if (key.equals(getString(R.string.room_picture_gallery))) {
                        Intent intent = new Intent(getContext(), FloorGalleryActivity.class);
                        intent.putExtra("type", type);
                        intent.putExtra("floorSerialNo", floorBean.getFloorSerialNo());
                        startActivity(intent);
                    } else if (key.equals("照相")) {
                        getImage(SelectImageActivity.ACTION_CAMERA);
                    } else {
                        getImage(SelectImageActivity.ACTION_GALLERY);

                    }
                }
            });
            mBottomListDialog.setAdapter(listLabelAdapter);
            new XPopup.Builder(getContext())
                    .dismissOnBackPressed(true)
                    .enableDrag(true)
                    .asCustom(mBottomListDialog);
        }
        ListLabelAdapter listLabelAdapter = (ListLabelAdapter) mBottomListDialog.getAdapter();
        mBottomListDialog.show();
    }

    private XXPermissions xxPermissions;

    private void getImage(String action) {
        currentAction = action; // 保存当前action
        if (xxPermissions == null) {
            xxPermissions = XXPermissions.with(getContext());
        }
        String[] permissions = new String[]{
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.CAMERA
        };
        if(!XXPermissions.isGranted(getContext(),permissions) && AppApplication.isHuawei() ){
            showConfirmHintDialog("App需要使用您的相机和存储权限，来拍摄和选择楼层图片。如若已拒绝，再使用本功能前请先前往手机设置中将本应用的相机和存储权限改为允许。");
        }else{
            requestPermission(action);
        }
    }

    private BaseDialog mConfirmHintDialog;
    private ConfirmHintDialog.Builder mConfirmHintDialogBuilder;

    private void showConfirmHintDialog(String text) {
        if (mConfirmHintDialog == null) {
            mConfirmHintDialogBuilder = new ConfirmHintDialog.Builder(getActivity())
                    .setRightBtnText(getString(R.string.ok))
                    .setListener(new ConfirmHintDialog.OnListener() {
                        @Override
                        public void onLeftClick(BaseDialog dialog) {
                            finish();
                        }

                        @Override
                        public void onConfirm(BaseDialog dialog) {
                            requestPermission(currentAction); // 使用保存的action
                        }
                    });
            mConfirmHintDialog = mConfirmHintDialogBuilder.create();
        }
        mConfirmHintDialogBuilder.setCancelable(false);
        mConfirmHintDialogBuilder.setContent(text);
        mConfirmHintDialog.show();
    }

    private void requestPermission(String action) {
        xxPermissions.permission(Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.CAMERA)
                .request(new OnPermissionCallback() {
                    @Override
                    public void onGranted(List<String> permissions, boolean all) {
                        if (all) {
                            actionProfilePic(action);
                        }
                    }

                    @Override
                    public void onDenied(List<String> permissions, boolean never) {
                        ToastUtils.show(R.string.common_permission_fail_1);
                    }

                });
    }

    private void actionProfilePic(String action) {
        Intent intent = new Intent(getContext(), SelectImageActivity.class);
        intent.setAction(SelectImageActivity.ACTION_RECT);
        intent.putExtra("ACTION", action);
        startActivityForResult(intent, new BaseActivity.OnActivityCallback() {
            @Override
            public void onActivityResult(int resultCode, @Nullable Intent data) {
                if (data != null && data.getExtras() != null) {
                    //在这里获得了剪裁后的Bitmap对象，可以用于上传
                    String imagePath = data.getExtras().getString(SelectImageActivity.CROP_IMAGE_PATH);
                    updateCropImage(new File(imagePath), true);
                }
            }
        });
    }

    private void updateCropImage(File file, boolean deleteFile) {
        if (file == null) return;
        showDialog();
        String path = String.format("room/custom/custom-%s-%d.jpg", floorBean.getFloorSerialNo(), System.currentTimeMillis());
        OBSManager.updateImage(path, file, new OBSManager.OBSCallBack() {
            @Override
            public void onSuccess(String imgUrl) {
                if (imgUrl != null) {
                    String imgpath = imgUrl.replace(OBS_BASE.substring(0, OBS_BASE.length() - 1), "");
                    savePic(imgpath);
                    hideDialog();
                    if (deleteFile) {
                        file.delete();
                    }
                }
            }

            @Override
            public void onFail() {
                hideDialog();
            }
        });
    }

    public void savePic(String path) {
//        if(type == 1){
            LLHttpManager.saveFloorPic(this, floorBean.getFloorSerialNo(), path, new HttpCallback<HttpData<Void>>(this) {
                @Override
                public void onStart(Call call) {
                    showDialog("请稍后");
                }

                @Override
                public void onSucceed(HttpData<Void> result) {
                    floorBean.setPicUrl(path);
                    LLFloorDBManager.getInstance(getContext()).put(floorBean);
                    EventBus.getDefault().post(new RefreshFloorRoomEvent());
                    finish();
                }

                @Override
                public void onFail(Exception e) {
                    ToastUtils.show(e.getMessage());
                }

                @Override
                public void onEnd(Call call) {
                    hideDialog();
                }
            });
//        }else{
//            LLHttpManager.saveHousePic(this, AppApplication.getInstance().getCurrentHouseSerialNo(), path, new HttpCallback<HttpData<Void>>(this) {
//                @Override
//                public void onStart(Call call) {
//                    showDialog("请稍后");
//                }
//
//                @Override
//                public void onSucceed(HttpData<Void> result) {
//                    floorBean.setPicUrl(path);
//                    LLFloorDBManager.getInstance(getContext()).put(floorBean);
//                    EventBus.getDefault().post(new RefreshFloorRoomEvent());
//                    finish();
//                }
//
//                @Override
//                public void onFail(Exception e) {
//                    ToastUtils.show(e.getMessage());
//                }
//
//                @Override
//                public void onEnd(Call call) {
//                    hideDialog();
//                }
//            });
//        }
    }
}